#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <stdlib.h>
#include <functional>
#include "InetAddr.hpp"
#include "Dict.hpp"

using namespace std;
const static int defaultsockfd = -1;
using func_t = function<string(const string&)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _port(port), _sockfd(defaultsockfd), _isrunning(false), _func(func)
    {
    }

    void InitServer()
    {
        // 创建socket套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket create fail, stringerrno: %s, errno: %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d", _sockfd);

        // 填充结构体sockaddr_in数据
        struct sockaddr_in local;                       // 栈上的
        bzero(&local, sizeof(local));                   // 清空
        local.sin_family = AF_INET;                     // 跨网络
        local.sin_port = htons(_port);                  // 主机序列 =》网络序列
        // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 主机序列 =》网络序列 && 10进制IP-》4字节IP
        local.sin_addr.s_addr = INADDR_ANY;

        // bind ip+port
        int n = bind(_sockfd, (sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind create fail, stringerrno: %s, errno: %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind create success");
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            // 服务端接收数据
            char request[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, request, sizeof(request) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                request[n] = 0;
                InetAddr addr(peer);// 传IP和PORT，知道谁发消息
                LOG(DEBUG, "get message from [%s:%d]: %s", addr.Ip().c_str(), addr.Port(), request);

                string responce = _func(request);// 回调，让外面执行

                //LOG(DEBUG, "get message: %s", buffer);
                // 发送接收的数据
                sendto(_sockfd, responce.c_str(), responce.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    //string _ip;
    uint16_t _port;
    bool _isrunning;

    // 设置回调
    func_t _func;
};